package net.tarine.gastronomi.server;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import net.tarine.gastronomi.server.model.ForumMessage;
import net.tarine.gastronomi.server.model.Gas;
import net.tarine.gastronomi.server.model.GasUser;
import net.tarine.gastronomi.shared.AppConst;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Mailer {

	private static final Log LOG = LogFactory.getLog(Mailer.class);
	
	public static void sendMessages(String fromAlias, Map<String, String> recipients, String subject, String msgBody) {
		Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(AppConst.APPLICATION_EMAIL, fromAlias));
            Set<String> recEmails = recipients.keySet();
            for (String email:recEmails) {
            	msg.addRecipient(Message.RecipientType.BCC,
                             new InternetAddress(email, recipients.get(email)));
            }
            msg.setSubject(subject);
            msg.setText(msgBody);
            Transport.send(msg);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
	}
	
	public static void sendNewMessageNotification(Gas gas, ForumMessage message, String messageUrl,
			GasUser author, List<GasUser> recipients) {
		String subject = "["+gas.getName()+"] "+message.getForumThread().getTitle();
		String fromAlias = gas.getName();
		String msgBody = "Questa e' una notifica.\r\n" +
				"Sul gruppo di discussione del gas "+fromAlias+
				" e' arrivato questo messaggio di "+author.getNickname()+":\r\n\r\n"+
				message.getText()+"\r\n\r\n"+
				"Puoi rispondere da questa pagina: " + messageUrl;
		Map<String, String> recMap = new HashMap<String, String>();
		for (GasUser user:recipients) {
			if (user.getEmail() != null) {
				String nick = user.getEmail();
				if (user.getNickname() != null) nick = user.getNickname();
				recMap.put(user.getEmail(), nick);
			}
		}
		sendMessages(fromAlias, recMap, subject, msgBody);
	}
}
